<?php

/*
 * Fresns Control Panel (Standalone)
 * Copyright (C) 2021-Present 刘鑫
 * Released under the MIT License.
 */

namespace App\Plugins\FcpApi\TweetMemberRoles;

use App\Base\Controllers\BaseAdminController;
use App\Http\Center\Common\ValidateService;
use App\Http\FresnsDb\FresnsMemberRoleRels\FresnsMemberRoleRels;
use App\Plugins\FcpApi\Base\TweetBaseController;
use Illuminate\Http\Request;

class FsControllerAdmin extends TweetBaseController
{
    public function __construct()
    {
        parent::__construct();
        $this->service = new FsService();
    }

    public function store(Request $request)
    {
        $request->offsetSet('permission', FsConfig::DEFAULT_PERMISSION);
        parent::store($request);
    }

    public function merge(Request $request)
    {
        // 校验参数
        $rule = [
            'role_id'    => 'required',
            'to_role_id'    => 'required',
        ];
        ValidateService::validateRule($request, $rule);

        $roleId = $request->input('role_id');
        $to_role_id = $request->input('to_role_id');

        $memberIdArr1 = FresnsMemberRoleRels::where('role_id', $roleId)->pluck('member_id')->toArray();
        $memberIdArr2 = FresnsMemberRoleRels::where('role_id', $to_role_id)->pluck('member_id')->toArray();

        $memberIdArr = [];
        foreach ($memberIdArr2 as $v) {
            if (! in_array($v, $memberIdArr1)) {
                $memberIdArr[] = $v;
            }
        }

        if ($memberIdArr) {
            FresnsMemberRoleRels::where('role_id', $to_role_id)->whereIn('member_id', $memberIdArr)->update(['role_id' => $roleId]);
        }

        FresnsMemberRoleRels::where('role_id', $to_role_id)->delete();

        $this->success();
    }

    // 验证规则
    public function rules($ruleType)
    {
        $rule = [];

        $config = new FsConfig($this->service->getTable());

        switch ($ruleType) {
            case FsConfig::RULE_STORE:
                $rule = $config->storeRule();
                break;

            case FsConfig::RULE_UPDATE:
                $rule = $config->updateRule();
                break;

            case FsConfig::RULE_DESTROY:
                $rule = $config->destroyRule();
                break;

            case FsConfig::RULE_DETAIL:
                $rule = $config->detailRule();
                break;
        }

        return $rule;
    }
}
